package com.raymond.thread.manager.pool;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 默认定时线程池
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2020-09-12 16:24
 */
@Configuration
@ConfigurationProperties(prefix = "java.default.scheduled.thread.pool")
@Data
@Component
public class DefaultScheduledThreadPool {

    /** 核心线程数（默认线程数）*/
    private int corePoolSize = 3;

    public static final String SCHEDULED_THREAD_POOL_NAME = "javaScheduledThreadExecutor";

    @Bean
    public ScheduledThreadPoolExecutor javaScheduledThreadExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("Java-Server-Scheduled-Executor-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return new ScheduledThreadPoolExecutor(corePoolSize, executor);
    }

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(2);
        return threadPoolTaskScheduler;
    }

}
